package top.wshape1.rpc.filter;

import top.wshape1.rpc.common.exception.RpcException;
import top.wshape1.rpc.message.RpcMessage;

import java.util.Iterator;
import java.util.PriorityQueue;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-13
 */

public class FilterChain {

    private final PriorityQueue<Filter> filters = new PriorityQueue<>((o1, o2) -> o2.getOrder() - o1.getOrder());

    private final ThreadLocal<Iterator<Filter>> iterator = new ThreadLocal<>();

    public void addFilter(Filter filter) {
        filters.add(filter);
    }

    public boolean doFilter(RpcMessage message) throws RpcException {
        if (iterator.get() == null)
            iterator.set(filters.iterator());
        if (iterator.get().hasNext()) {
            Filter filter = iterator.get().next();
            return filter.doFilter(message, this);
        }
        return true;
    }

    public void clearLocal() {
        iterator.remove();
    }

}
